package com.cyl.manager.pms.domain.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.domain.service.ProductDomainService;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.pms.req.ProductQueryReq;
import com.sincere.common.utils.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author: lsh
 * @create: 2025-01-22 14:50
 **/
@Service
public class ProductDomainServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductDomainService {

    private final ProductMapper productMapper;

    public ProductDomainServiceImpl(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Override
    public List<Product> listByPage(ProductQueryReq query, Pageable page) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(query.getSearch()),Product.COL_NAME, query.getSearch());
        queryWrapper.eq(Objects.nonNull(query.getSort()),Product.COL_SORT, query.getSort());
        queryWrapper.eq(Objects.nonNull(query.getCategoryId()),Product.COL_CATEGORY_ID, query.getCategoryId());
        queryWrapper.eq(Objects.nonNull(query.getPublishStatus()),Product.COL_PUBLISH_STATUS, query.getPublishStatus());
        queryWrapper.notIn(CollectionUtil.isNotEmpty(query.getExcludeProductIds()),Product.COL_ID, query.getExcludeProductIds());
        queryWrapper.in(CollectionUtil.isNotEmpty(query.getIds()),Product.COL_ID, query.getIds());
        queryWrapper.orderByAsc(Product.COL_SORT);

        QueryWrapper<Product> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(query.getOrderField())){
            if (StringUtils.isNotEmpty(query.getOrderSort()) && "desc".equalsIgnoreCase(query.getOrderSort())) {
                queryWrapper.orderByDesc(query.getOrderField());
            } else {
                queryWrapper.orderByAsc(query.getOrderField());
            }
        }else {
            queryWrapper.orderByDesc("publish_status");
            queryWrapper.orderByAsc("sort");
        }

        return productMapper.selectList(queryWrapper);
    }

    @Override
    public List<Product> ListAllPage() {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc(Product.COL_SORT);
        return productMapper.selectList(queryWrapper);
    }
}
